package org.mayuanxiaonong.timserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

import org.mayuanxiaonong.timserver.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Bootstrap {
	
	private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);

	private static Bootstrap instance = null;
	
	private Config config = Config.getInstance();
	
	public Bootstrap() {
		if (instance != null) {
			throw new IllegalStateException("Server is already running");
		}
		instance = this;

		startup();
	}

	/**
	 * 启动服务
	 */
	public void startup() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			SelfSignedCertificate ssc = new SelfSignedCertificate();
			SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
			
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workGroup);
			b.channel(NioServerSocketChannel.class);
			b.option(ChannelOption.SO_BACKLOG, 128);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.childHandler(new ServerInitializer(sslCtx));
			
			ChannelFuture future = b.bind(config.getServerHost(), config.getServerPort()).sync();
			
			log.info("Server startup successful, listen on " + config.getServerPort());
			
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			log.error("Server startup failed", e);
			System.exit(1);
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

}
